package com.doudou.oauth.request;

import org.springframework.security.oauth2.common.exceptions.InvalidScopeException;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestValidator;

import java.util.Set;

/**
 * @Author: 允许 Empty request scopes
 * @Date: 2020/6/10 9:32
 * @Version: 1.0
 * @Description: 请求效验
 */
public class CustomizeOAuth2RequestValidator extends DefaultOAuth2RequestValidator {

    @Override
    public void validateScope(AuthorizationRequest authorizationRequest, ClientDetails client) throws InvalidScopeException {
        validateScope(authorizationRequest.getScope(), client.getScope());
    }

    @Override
    public void validateScope(TokenRequest tokenRequest, ClientDetails client) throws InvalidScopeException {
        validateScope(tokenRequest.getScope(), client.getScope());
    }


    private void validateScope(Set<String> requestScopes, Set<String> clientScopes) {

        if (clientScopes != null && !clientScopes.isEmpty()) {
            for (String scope : requestScopes) {
                if (!clientScopes.contains(scope)) {
                    throw new InvalidScopeException("Invalid scope: " + scope, clientScopes);
                }
            }
        }

//        if (requestScopes.isEmpty()) {
//            throw new InvalidScopeException("Empty scope (either the client or the user is not allowed the requested scopes)");
//        }
    }
}
